package com.wyl.servlet

import java.time.LocalDateTime
import javax.servlet.annotation.WebServlet
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 获取用户上一次访问的时间
 */
@WebServlet("/cookie01")
class CookieServlet01 : HttpServlet() {
    override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
        println("CookieServlet01...")
        req.characterEncoding = "utf-8"
        resp.contentType = "text/html;charset=UTF-8"
        // cookies可以存在多个
        println(req.cookies)
        resp.writer.use { writer ->
            req.cookies.find { it.name == "time" }.let {
                if (it == null) {
                    writer.write("这是您第一次访问本站")
                } else {
                    writer.write("您上一次的访问时间为 + ${it.value}")
                }
            }

            // 服务器给客户端发一个cookie
            resp.addCookie(Cookie("time", LocalDateTime.now().toString()))
        }
    }

    override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
        doPost(req, resp)
    }
}